import * as fs from 'node:fs'
import { parse, stringify } from 'json5'

addArkoalaMetadata(process.argv[2])

function addArkoalaMetadata(modulePath: string): void {
    try {
        const moduleStr = fs.readFileSync(modulePath, { encoding: 'utf8', flag: 'r' })
        const moduleJson = parse(moduleStr)
        if (moduleJson.module !== undefined) {
            if ((moduleJson.module.metadata?.length ?? 0) === 0) {
                moduleJson.module.metadata = []
            }
            let hasArkoalaPlugin = false
            for (let i = 0; i < moduleJson.module.metadata.length; ++i) {
                if (moduleJson.module.metadata[i].name === 'ArkoalaPlugin') {
                    moduleJson.module.metadata[i] = { name: 'ArkoalaPlugin', value: 'true' }
                    hasArkoalaPlugin = true
                }
            }
            if (!hasArkoalaPlugin) {
                moduleJson.module.metadata.push({ name: 'ArkoalaPlugin', value: 'true' })
            }
            const newModuleStr = stringify(moduleJson, null, 2)
            fs.writeFileSync(modulePath, newModuleStr, 'utf8')
            console.info("Updated: " + modulePath)
        } else {
            throw new Error('module.json5 format error.')
        }
    } catch (err) {
        console.error('Error: ' + err)
        console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        console.warn('\x1b[33m%s\x1b[0m', `WARNING module.json5 is not created. ${modulePath}`)
        console.warn('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
    }
}
